/* eslint-disable array-callback-return */
import React, { Component } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Row,
  Col,
  Spin,
  Select,
  Input,
  InputNumber,
  Table,
  Radio,
  Divider,
  Cascader,
  Popconfirm,
  message,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import SendRecvSupplier from '../../components/SendRecvSupplier';
import DictCode from '../../components/DictCode';
import CustOrSupp from './CustOrSupp';
import SelectInvMail from './SelectInvMail';
import { urlParse } from '@/utils/utils';

import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Option } = Select;

@connect(
  ({
    editinvrule: {
      invRuleInfo,
      custSuppType,
      tableId,
      contList,
      invRulePanyTermMailDto,
      invMailData,
      invMailType,
      invMailId,
    },
    publicdata,
    loading,
    login: { systemList },
  }) => ({
    loading:
      loading.effects['editinvrule/fetchCustSuppList'] ||
      loading.effects['editinvrule/fetchContList'] ||
      loading.effects['editinvrule/fetchInvTermList'] ||
      loading.effects['editinvrule/getAreaList']
        ? false
        : loading.models.editinvrule,
    invTermListLoading: loading.effects['editinvrule/fetchInvTermList'],
    selectMailLoading: loading.effects['editinvrule/getAreaList'],
    fetching: loading.effects['editinvrule/fetchContList'],
    systemList,
    dictCode: publicdata.dictCode,
    invRuleInfo,
    custSuppType,
    contList,
    invRulePanyTermMailDto,
    tableId, // 表格行标识
    invMailData,
    invMailType, // 发票2邮寄地址
    invMailId,
  })
)
@Form.create()
class EditInvRule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      invRuleId: null,
      isUpdate: false,
      isDisabledSerType: false,
      sysCode: 1,
      provCityAreaList: [],
      modalVisible: false,
    };
  }

  componentDidMount() {
    const { dispatch, systemList, location } = this.props;
    const { invRuleId = null, isUpdate } = urlParse(location.search);
    const { sysCode } = systemList.filter(item => item.isSelected)[0];
    this.setState({
      sysCode,
      invRuleId,
      isUpdate: isUpdate === 'true',
    });
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['FM_INV_RULE_TYPE', 'FM_INV_FEE_TYPE', 'FM_INV_RULE_WAY'],
    });
    dispatch({
      type: 'editinvrule/fetchPdList',
      payload: {},
    });
    if (sysCode === 2) {
      // 供应商交互系统
      dispatch({
        type: 'editinvrule/updateModelData',
        payload: {
          custSuppType: '2',
        },
      });
      dispatch({
        type: 'editinvrule/updateRuleInfo',
        payload: {
          serType: '1',
          serTypeName: '委托',
          fullyFlag: '2',
          fullyFlagName: '否',
        },
      });
    }
    if (invRuleId) {
      // 修改
      dispatch({
        type: 'editinvrule/fetchUpdateInfo',
        payload: { invRuleId },
      }).then(data => {
        if (data) {
          if (data.custSuppId) {
            // 获取邮寄地址信息
            dispatch({
              type: 'editinvrule/fetchInvOrMailInfo',
              payload: {
                custSuppId: data.custSuppId,
                custSuppType: `${data.custSuppType}`,
                sysCode,
              },
            });
          }
          if (data.invRulePanyTermMailDto && data.invRulePanyTermMailDto.length) {
            // 获取地区数据
            this.getAreaList(null, d => {
              d.map(i => {
                const temp = i;
                temp.label = i.areaName;
                temp.value = i.areaId;
                temp.isLeaf = false;
              });
              this.setState({ provCityAreaList: d }, () => {
                data.invRulePanyTermMailDto.map(item => {
                  if (
                    item.invMail &&
                    item.invMail.invPay === 1 &&
                    item.invMail.areaList &&
                    item.invMail.areaList.length
                  ) {
                    const areaIdList = [];
                    item.invMail.areaList.forEach(a => {
                      areaIdList.push(a.areaId);
                    });
                    // 获取地区数据
                    this.getProvCityAreaList(areaIdList);
                  }
                });
              });
            });
          }
        }
      });
    } else {
      // 获取地区数据
      this.getAreaList(null, data => {
        data.map(item => {
          const temp = item;
          temp.label = item.areaName;
          temp.value = item.areaId;
          temp.isLeaf = false;
        });
        this.setState({ provCityAreaList: data });
      });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'editinvrule/updateModelData',
      payload: {
        custList: [],
        suppList: [],
        custSuppType: '1', // 选择1客户 2供应商
        invRuleInfo: {},
        contList: [], // 合同列表
        invRulePanyTermMailDto: [], // 发票信息集合
        pdList: [], // 产品列表
        invList: [], // 发票信息列表
        MailList: [], // 邮寄地址列表
        invTermList: [], // 开票项目列表
        invMailData: [], // 发票抬头与邮寄地址数据
      },
    });
  }

  // 选择客户或供应商
  selectCustSupp = (value, option) => {
    const {
      form,
      dispatch,
      invRuleInfo: { serType, invType, invTypeName },
    } = this.props;
    const { sysCode } = this.state;
    const { fsOptions } = option.props;
    form.resetFields(['contId']);
    // 获取邮寄地址信息
    dispatch({
      type: 'editinvrule/fetchInvOrMailInfo',
      payload: { custSuppId: value.key, custSuppType: (fsOptions.custId && '1') || '2', sysCode },
    });
    dispatch({
      type: 'editinvrule/updateModelData',
      payload: {
        custSuppType: (fsOptions.custId && '1') || '2',
      },
    });
    if (invType && invTypeName) {
      dispatch({
        type: 'editinvrule/resetInvOrMailInfo',
      });
      this.resetInvOrMailForm();
      this.selectInvType({ key: invType, label: invTypeName });
    }
    dispatch({
      type: 'editinvrule/updateRuleInfo',
      payload: {
        custSuppId: value.key,
        serType: (!fsOptions.custId && fsOptions.suppId && '1') || serType,
        contId: undefined,
      },
    });
    form.setFieldsValue({ serType: (!fsOptions.custId && fsOptions.suppId && '1') || serType });
    this.setState({ isDisabledSerType: (!fsOptions.custId && fsOptions.suppId && true) || false });
  };

  // 选择服务类型
  selectSerType = value => {
    const { form, dispatch } = this.props;
    form.resetFields(['contId']);
    dispatch({
      type: 'editinvrule/updateRuleInfo',
      payload: {
        serType: value,
        contId: undefined,
      },
    });
  };

  // 获取合同列表
  getContList = (custSuppType, custSuppId, serType) => {
    const { dispatch } = this.props;
    const { sysCode } = this.state;
    if (!custSuppId) {
      return message.warning(sysCode === 1 ? '请先选择客户/供应商！' : '请先选择签约方！');
    }
    if (!serType) {
      return message.warning('请先选择服务类型！');
    }
    dispatch({
      type: 'editinvrule/fetchContList',
      payload: { custSuppType, custSuppId, serType },
    });
    return true;
  };

  // 选择合同
  selectCont = value => {
    const {
      dispatch,
      invRuleInfo: { serType },
    } = this.props;
    dispatch({
      type: 'editinvrule/fetchContInfo',
      payload: {
        contId: value.key,
        serType,
      },
    });
  };

  // 选择签约方
  selectSupply = value => {
    const {
      dispatch,
      invRuleInfo: { invType, invTypeName },
    } = this.props;
    const { sysCode } = this.state;
    dispatch({
      type: 'editinvrule/updateRuleInfo',
      payload: {
        custSuppId: value.key,
        custSuppType: '2',
      },
    });
    dispatch({
      type: 'editinvrule/fetchInvOrMailInfo',
      payload: { custSuppId: value.key, custSuppType: '2', sysCode },
    });
    if (invType && invTypeName) {
      dispatch({
        type: 'editinvrule/resetInvOrMailInfo',
      });
      this.resetInvOrMailForm();
      this.selectInvType({ key: invType, label: invTypeName });
    }
  };

  // 选择发票规则
  selectInvType = value => {
    const {
      dispatch,
      dictCode: { FM_INV_RULE_WAY },
    } = this.props;
    dispatch({
      type: 'editinvrule/selectInvType',
      payload: {
        invType: value.key,
        invTypeName: value.label,
        invPayList: FM_INV_RULE_WAY,
      },
    });
  };

  // 选择发票交付方式
  selectInvPay = (e, id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'editinvrule/setRuleDto',
      payload: {
        targetKey: 'invPay',
        parentKey: 'invMail',
        value: e.target.value,
        id,
      },
    });
  };

  // 选择发票抬头或邮寄地址
  selectInvOrMail = (invMailType, id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'editinvrule/updateInvOrMailList',
      payload: { invMailType, invMailId: id },
    });
    this.setState({ modalVisible: true });
  };

  // 保存选择发票或者邮寄地址的数据
  saveInvOrMail = record => {
    const { invMailType, invMailId } = this.props;
    const { sysCode } = this.state;
    let invOrMailInfo = {};
    if (invMailType === '1') {
      // 发票抬头
      const {
        vatCoprName: holderName,
        taxerIdNo,
        bankOfDepoName,
        invPhone: phone,
        bankAcco,
        invAddr: holderAddrs,
      } = record;
      invOrMailInfo = {
        holderName,
        taxerIdNo,
        holderAddrs: sysCode === 1 ? holderAddrs : record.invArea,
        phone,
        bankOfDepoName: sysCode === 1 ? bankOfDepoName : record.openBank,
        bankAcco,
      };
      this.saveMailInfo(invMailId, invMailType, invOrMailInfo);
    } else {
      // 邮寄地址
      const { contPerName, contPerPhone, mailAddr, areaList } = record;
      const mailArea = [];
      const areaIdList = [];
      if (areaList.length) {
        areaList.forEach(item => {
          areaIdList.push(item.areaId);
          mailArea.push(item.areaId);
        });
        invOrMailInfo = {
          contPerName,
          contPerPhone,
          mailArea,
          mailAddr,
        };
        this.getProvCityAreaList(areaIdList, () =>
          this.saveMailInfo(invMailId, invMailType, invOrMailInfo)
        );
      }
    }
  };

  // 获取省市区回显
  getProvCityAreaList = (areaIdList, callback) => {
    const { provCityAreaList } = this.state;
    const cityData = [];
    const countyData = [];
    switch (areaIdList.length) {
      case 1:
        if (callback) callback();
        break;
      case 2:
        this.getAreaList(areaIdList[0], data => {
          data.map(area => {
            cityData.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            if (p.areaId === areaIdList[0]) {
              const temp = p;
              temp.children = cityData;
            }
          });
          this.setState({ provCityAreaList }, () => {
            if (callback) callback();
          });
        });
        break;
      case 3:
        // 获取市
        this.getAreaList(areaIdList[0], data => {
          data.map(area => {
            cityData.push({
              label: area.areaName,
              value: area.areaId,
              isLeaf: area.areaNature === 6,
            });
          });
          provCityAreaList.map(p => {
            const temp = p;
            if (p.areaId === areaIdList[0]) {
              temp.children = cityData;
            }
          });
          // 获取区县
          this.getAreaList(areaIdList[1], datas => {
            datas.map(area => {
              countyData.push({
                label: area.areaName,
                value: area.areaId,
                isLeaf: area.areaNature === 6,
              });
            });
            provCityAreaList.map(p => {
              if (p.areaId === areaIdList[0]) {
                // 判断省
                p.children.map(c => {
                  const temp = c;
                  if (c.value === areaIdList[1]) {
                    // 判读市
                    temp.children = countyData;
                  }
                });
              }
            });
            this.setState({ provCityAreaList }, () => {
              if (callback) callback();
            });
          });
        });
        break;
      default:
        break;
    }
  };

  // 保存邮寄地址信息
  saveMailInfo = async (invMailId, invMailType, invOrMailInfo) => {
    const { form, dispatch } = this.props;
    await dispatch({
      type: 'editinvrule/saveInvOrMail',
      payload: { invMailId, invMailType, invOrMailInfo },
    });
    await this.handleModalVisible(false);
    const { invRulePanyTermMailDto } = form.getFieldsValue();
    invRulePanyTermMailDto
      .filter(item => item)
      .map(item => {
        if ((item.invCompany && item.invCompany.invType) === invMailId) {
          if (invMailType === '1') {
            Object.keys(item.invCompany).forEach(key => {
              if (key !== 'invType' && key !== 'invTypeName' && key !== 'remark') {
                form.setFieldsValue({
                  [`invRulePanyTermMailDto[${invMailId}][invCompany][${key}]`]: invOrMailInfo[key],
                });
              }
            });
          } else {
            Object.keys(item.invMail).forEach(key => {
              if (key !== 'invPay' && key !== 'invPayName' && key !== 'email') {
                form.setFieldsValue({
                  [`invRulePanyTermMailDto[${invMailId}][invMail][${key}]`]: invOrMailInfo[key],
                });
              }
            });
          }
        }
      });
  };

  // 选择客户/供应商/签约方重置发票与邮寄地址信息
  resetInvOrMailForm = () => {
    const { form } = this.props;
    const { invRulePanyTermMailDto } = form.getFieldsValue();
    invRulePanyTermMailDto
      .filter(item => item)
      .map(item => {
        Object.keys(item.invCompany).forEach(key => {
          if (key !== 'invType' && key !== 'invTypeName' && key !== 'remark') {
            form.resetFields([
              `invRulePanyTermMailDto[${parseInt(
                item.invCompany && item.invCompany.invType,
                10
              )}][invCompany][${key}]`,
            ]);
          }
        });
        Object.keys(item.invMail).forEach(key => {
          if (key !== 'invPay' && key !== 'invPayName' && key !== 'email') {
            form.resetFields([
              `invRulePanyTermMailDto[${parseInt(
                item.invCompany && item.invCompany.invType,
                10
              )}][invMail][${key}]`,
            ]);
          }
          if (key === 'invPay') {
            form.setFieldsValue({
              [`invRulePanyTermMailDto[${parseInt(
                item.invCompany && item.invCompany.invType,
                10
              )}][invMail][${key}]`]: '2',
            });
          }
        });
      });
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  // 新增发票项目列表
  addInvTermList = id => {
    const { dispatch, invRulePanyTermMailDto } = this.props;
    invRulePanyTermMailDto.map(item => {
      const temp = item;
      if (item.id === id) {
        temp.tableId += 1;
        if (temp.invTerm) {
          temp.invTerm.push({
            id: item.id,
            key: item.tableId,
            pdList: item.pdList,
            pdId: undefined,
            invTermList: [],
            bilingType: undefined,
            invTerm: undefined,
            invRatio: undefined,
          });
        }
      }
    });
    dispatch({
      type: 'editinvrule/updateModelData',
      payload: { invRulePanyTermMailDto: JSON.parse(JSON.stringify(invRulePanyTermMailDto)) },
    });
  };

  // 删除发票项目列表
  delInvTermList = (id, key) => {
    const { dispatch, invRulePanyTermMailDto } = this.props;
    invRulePanyTermMailDto.map(item => {
      if (item.id === id) {
        const temp = item;
        temp.invTerm = item.invTerm && item.invTerm.filter(c => c.key !== key);
      }
    });
    dispatch({
      type: 'editinvrule/updateModelData',
      payload: { invRulePanyTermMailDto: JSON.parse(JSON.stringify(invRulePanyTermMailDto)) },
    });
  };

  // 选择发票项目
  selectTerm = (targetKey, value, id, key, option) => {
    const { dispatch, invRulePanyTermMailDto } = this.props;
    let pdId = null;
    let bilingType = null;
    invRulePanyTermMailDto.map(item => {
      if (item.id === id && item.invTerm && item.invTerm.length) {
        item.invTerm.map(c => {
          const temp = c;
          if (c.key === key) {
            temp[targetKey] = value;
            const temps = c.pdId;
            pdId = temps;
            const tempbilingType = c.bilingType;
            bilingType = tempbilingType;
            if (targetKey === 'invTerm') {
              const { fsOptions } = option.props;
              temp.invRatio = parseFloat(fsOptions.invRatio) || null;
            }
          }
        });
      }
    });
    dispatch({
      type: 'editinvrule/updateModelData',
      payload: { invRulePanyTermMailDto: JSON.parse(JSON.stringify(invRulePanyTermMailDto)) },
    });
    if (targetKey === 'pdId' && bilingType) {
      this.getInvTermList(id, key, value, bilingType, true);
    }
    if (targetKey === 'bilingType' && pdId) {
      this.getInvTermList(id, key, pdId, value, true);
    }
  };

  // 获取开票项目列表
  getInvTermList = (id, key, pdId, bilingType, isClearForm) => {
    const {
      form,
      dispatch,
      invRuleInfo: { serType },
    } = this.props;
    if (pdId && bilingType) {
      if (isClearForm) {
        form.resetFields([`invRulePanyTermMailDto[${id}][invTerm[${key}][invTerm]]`]);
        dispatch({
          type: 'editinvrule/setRuleDto',
          payload: { targetKey: 'invTerm', parentKey: 'invTerm', value: undefined, id, key },
        });
      }
      dispatch({
        type: 'editinvrule/setRuleDto',
        payload: {
          targetKey: 'invTermList',
          parentKey: 'invTerm',
          value: [],
          id,
          key,
        },
      });
      dispatch({
        type: 'editinvrule/fetchInvTermList',
        payload: { id, key, serType, pdId, bilingType },
      });
    }
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'editinvrule/getAreaList',
      payload: {
        parentId: areaId,
      },
    }).then(res => {
      callback(res.data);
    });
  };

  // 地区选择：省市区
  selectProvCityArea = (value, selectedOptions, id) => {
    const { dispatch } = this.props;
    if (value.length > 1) {
      dispatch({
        type: 'editinvrule/setRuleDto',
        payload: {
          targetKey: 'mailArea',
          parentKey: 'invMail',
          value,
          id,
        },
      });
    }
  };

  // 动态加载
  loadAreaData = selectedOptions => {
    const { provCityAreaList } = this.state;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].value;
    targetOption.loading = true;
    const childrenData = [];
    this.getAreaList(parentId, data => {
      data.map(item => {
        const temp = item;
        temp.isLeaf = item.areaNature === 6;
        temp.label = item.areaName;
        temp.value = item.areaId;
        childrenData.push(item);
      });
    });
    // load options lazily
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        provCityAreaList: [...provCityAreaList],
      });
    }, 1000);
  };

  // 提交数据
  submitData = () => {
    const { dispatch, form } = this.props;
    const { invRuleId, isUpdate, sysCode } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'editinvrule/submit',
          payload: { values, invRuleId, isUpdate, sysCode },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      invRuleInfo: {
        custSuppId,
        custSuppName,
        serType,
        serTypeName = '--',
        contId,
        contName = '--',
        fullyFlag,
        fullyFlagName = '--',
        invType,
        invTypeName = '--',
        invQuota,
      },
      contList,
      invRulePanyTermMailDto,
      invMailData,
      invMailType,
      loading,
      invTermListLoading,
      selectMailLoading,
      custSuppType,
      fetching,
    } = this.props;
    const {
      sysCode,
      invRuleId,
      isUpdate,
      isDisabledSerType,
      provCityAreaList,
      modalVisible,
    } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 14 } },
    };

    const columns = invTerm => [
      {
        title: '序号',
        dataIndex: 'number',
        align: 'center',
        width: '10%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        onCell: () => ({
          style: {
            paddingTop: 0,
          },
        }),
        render: (text, record, index) => <span>{index + 1}</span>,
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        align: 'center',
        width: '25%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        render: (text, record) => (
          <FormItem>
            {getFieldDecorator(
              `invRulePanyTermMailDto[${record.id}][invTerm[${record.key}][pdId]]`,
              {
                rules: [{ required: true, message: '请选择' }],
                initialValue: record.pdId,
              }
            )(
              <Select
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                notFoundContent="暂无数据"
                onSelect={value => this.selectTerm('pdId', value, record.id, record.key)}
              >
                {record.pdList &&
                  record.pdList.length &&
                  record.pdList.map(item => <Option key={item.pdId}>{item.pdName}</Option>)}
              </Select>
            )}
          </FormItem>
        ),
      },
      {
        title: '费用类型',
        dataIndex: 'bilingType',
        align: 'center',
        width: '20%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        render: (text, record) => (
          <FormItem>
            {getFieldDecorator(
              `invRulePanyTermMailDto[${record.id}][invTerm[${record.key}][bilingType]]`,
              {
                rules: [{ required: true, message: '请选择' }],
                initialValue: record.bilingType && `${record.bilingType}`,
              }
            )(
              <DictCode
                placeholder="请选择"
                dictType="FM_INV_FEE_TYPE"
                onSelect={value => this.selectTerm('bilingType', value, record.id, record.key)}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '开票项目',
        dataIndex: 'invTerm',
        align: 'center',
        width: '25%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        render: (text, record) => (
          <FormItem>
            {getFieldDecorator(
              `invRulePanyTermMailDto[${record.id}][invTerm[${record.key}][invTerm]]`,
              {
                rules: [{ required: true, message: '请选择' }],
                initialValue: record.invTerm && `${record.invTerm}`,
              }
            )(
              <Select
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                notFoundContent={invTermListLoading ? <Spin size="small" /> : null}
                onSelect={(value, option) =>
                  this.selectTerm('invTerm', value, record.id, record.key, option)
                }
                onFocus={() =>
                  this.getInvTermList(
                    record.id,
                    record.key,
                    record.pdId,
                    record.bilingType && `${record.bilingType}`
                  )
                }
              >
                {record.invTermList &&
                  record.invTermList.length &&
                  record.invTermList.map(item => (
                    <Option key={item.termId} fsOptions={item}>
                      {item.invTerm}
                    </Option>
                  ))}
              </Select>
            )}
          </FormItem>
        ),
      },
      {
        title: '税率',
        dataIndex: 'invRatio',
        align: 'center',
        width: '10%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        render: (text, record) => (
          <FormItem>
            {getFieldDecorator(
              `invRulePanyTermMailDto[${record.id}][invTerm[${record.key}][invRatio]]`,
              {
                rules: [{ required: false, message: '请选择' }],
                initialValue: record.invRatio,
              }
            )(
              <span>
                {(record.invRatio && `${record.invRatio}%`) || (record.invRatio === 0 ? 0 : '--')}
              </span>
            )}
          </FormItem>
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        width: '10%',
        onHeaderCell: () => ({ style: { textAlign: 'center', fontWeight: 'bold' } }),
        onCell: () => ({
          style: {
            paddingTop: 0,
          },
        }),
        render: (text, record) =>
          invTerm.length > 1 ? (
            <Popconfirm
              title="确定要删除此行？"
              onConfirm={() => this.delInvTermList(record.id, record.key)}
            >
              <a>删除</a>
            </Popconfirm>
          ) : (
            '--'
          ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading || false}>
          <Form layout="horizontal" className={styles.pdSet}>
            <Card title="客户信息">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24} pull={1}>
                  {sysCode === 1 ? (
                    <FormItem label="客户/供应商" {...formItemLayout}>
                      {getFieldDecorator('custSuppId', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: custSuppId && { key: custSuppId, label: custSuppName },
                      })(
                        <CustOrSupp
                          labelInValue
                          getData={this.selectCustSupp}
                          disabled={isUpdate}
                        />
                      )}
                    </FormItem>
                  ) : (
                    <FormItem label="签约方" {...formItemLayout}>
                      {getFieldDecorator('custSuppId', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: custSuppId && { key: custSuppId, label: custSuppName },
                      })(
                        <SendRecvSupplier
                          labelInValue
                          getData={this.selectSupply}
                          placeholder="请选择"
                          disabled={isUpdate}
                        />
                      )}
                    </FormItem>
                  )}
                </Col>
                <Col md={8} sm={24} pull={1}>
                  <FormItem label="服务类型" {...formItemLayout}>
                    {getFieldDecorator('serType', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: serType && `${serType}`,
                    })(
                      sysCode === 2 ? (
                        <span>{serTypeName}</span>
                      ) : (
                        <DictCode
                          placeholder="请选择"
                          dictType="SER_TYPE"
                          disabled={(invRuleId && true) || false || isDisabledSerType}
                          onSelect={this.selectSerType}
                        />
                      )
                    )}
                  </FormItem>
                </Col>
                {sysCode === 1 && (
                  <Col md={8} sm={24} pull={1}>
                    <FormItem label="合同名称" {...formItemLayout}>
                      {getFieldDecorator('contId', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: isUpdate
                          ? contId && { key: contId, label: contName }
                          : undefined,
                      })(
                        <Select
                          labelInValue
                          placeholder="请选择"
                          onSelect={this.selectCont}
                          showSearch
                          optionFilterProp="children"
                          onFocus={() => this.getContList(custSuppType, custSuppId, serType)}
                          notFoundContent={fetching ? <Spin size="small" /> : null}
                        >
                          {contList &&
                            contList.length &&
                            contList.map(item => (
                              <Option key={item.contId} fsOptions={item}>
                                {item.contName}
                              </Option>
                            ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                )}
                <Col md={8} sm={24} pull={1}>
                  <FormItem label="是否全额计税" {...formItemLayout}>
                    {getFieldDecorator('fullyFlag', {
                      rules: [{ required: false, message: '请选择' }],
                      initialValue: fullyFlag && `${fullyFlag}`,
                    })(<span>{fullyFlagName}</span>)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} pull={1}>
                  <FormItem label="开票类型" {...formItemLayout}>
                    {getFieldDecorator('invType', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue:
                        (invType && { key: `${invType}`, label: invTypeName }) || undefined,
                    })(
                      <DictCode
                        labelInValue
                        placeholder="请选择"
                        dictType="FM_INV_RULE_TYPE"
                        onSelect={this.selectInvType}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} pull={1}>
                  <FormItem label="单张发票限额(元)" {...formItemLayout}>
                    {getFieldDecorator('invQuota', {
                      rules: [
                        {
                          required: false,
                          message: '请输入小数点不超过2位的数字',
                          pattern: /^-?\d+\.?\d{0,2}$/,
                        },
                      ],
                      initialValue: invQuota,
                    })(
                      <InputNumber
                        min={0}
                        max={9999999.99}
                        placeholder="请输入"
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            {invType && (
              <Card title="发票信息">
                {invRulePanyTermMailDto &&
                  invRulePanyTermMailDto.length &&
                  invRulePanyTermMailDto.map((item, index) => (
                    <div key={item.id}>
                      {index > 0 && <Divider />}
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="开票类型" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][invType]`,
                              {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: item.invCompany && item.invCompany.invType,
                              }
                            )(
                              <span style={{ position: 'relative' }}>
                                {(item.invCompany && item.invCompany.invTypeName) || '--'}
                                {item.invList && item.invList.length ? (
                                  <a
                                    style={{
                                      position: 'absolute',
                                      right: '-80px',
                                      top: '-2px',
                                      display: 'block',
                                      width: 60,
                                    }}
                                    onClick={() => this.selectInvOrMail('1', item.id)}
                                  >
                                    选择抬头
                                  </a>
                                ) : null}
                              </span>
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="单位名称" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][holderName]`,
                              {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue: item.invCompany && item.invCompany.holderName,
                              }
                            )(<Input placeholder="请输入" maxLength={100} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="纳税人识别号" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][taxerIdNo]`,
                              {
                                rules: [
                                  {
                                    required: true,
                                    message: '最大长度不超过18位的数字或字母',
                                    pattern: /^[a-zA-Z0-9]{1,18}$/,
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.taxerIdNo,
                              }
                            )(<Input placeholder="请输入" maxLength={19} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="单位地址" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][holderAddrs]`,
                              {
                                rules: [
                                  {
                                    required: item.invCompany && item.invCompany.invType === '3',
                                    message: '请输入',
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.holderAddrs,
                              }
                            )(<Input placeholder="请输入" maxLength={100} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="电话" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][phone]`,
                              {
                                rules: [
                                  {
                                    required: item.invCompany && item.invCompany.invType === '3',
                                    message: '固话或手机',
                                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.phone,
                              }
                            )(<Input placeholder="请输入" maxLength={12} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="开户行" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][bankOfDepoName]`,
                              {
                                rules: [
                                  {
                                    required: item.invCompany && item.invCompany.invType === '3',
                                    message: '请输入',
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.bankOfDepoName,
                              }
                            )(<Input placeholder="请输入" maxLength={100} />)}
                          </FormItem>
                        </Col>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="银行帐号" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][bankAcco]`,
                              {
                                rules: [
                                  {
                                    required: item.invCompany && item.invCompany.invType === '3',
                                    message: '最大长度不超过25的数字',
                                    pattern: /^\d{1,25}$/,
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.bankAcco,
                              }
                            )(<Input placeholder="请输入" maxLength={25} />)}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{ maxWidth: 1000 }}>
                        <Col offset={1}>
                          <Table
                            dataSource={item.invTerm}
                            columns={columns(item.invTerm)}
                            bordered
                            rowKey={(record, i) => i}
                            pagination={false}
                            className={styles.rowPadding}
                          />
                          <Button
                            style={{ width: '100%', margin: '24px 0' }}
                            type="dashed"
                            icon={<PlusOutlined />}
                            onClick={() => this.addInvTermList(item.id)}
                          >
                            新增
                          </Button>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem label="备注" {...formItemLayout}>
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invCompany][remark]`,
                              {
                                rules: [
                                  {
                                    required: false,
                                    message: '请输入',
                                  },
                                ],
                                initialValue: item.invCompany && item.invCompany.remark,
                              }
                            )(<Input placeholder="请输入" maxLength={200} />)}
                          </FormItem>
                        </Col>
                      </Row>
                      <Divider dashed />
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={8} sm={24} pull={1}>
                          <FormItem
                            label="发票交付方式"
                            {...formItemLayout}
                            style={{ position: 'relative' }}
                          >
                            {getFieldDecorator(
                              `invRulePanyTermMailDto[${item.id}][invMail][invPay]`,
                              {
                                rules: [{ required: true, message: '请选择' }],
                                initialValue:
                                  item.invMail && item.invMail.invPay && `${item.invMail.invPay}`,
                              }
                            )(
                              <RadioGroup onChange={value => this.selectInvPay(value, item.id)}>
                                {item.invMail &&
                                  item.invMail.invPayList &&
                                  item.invMail.invPayList.length &&
                                  item.invMail.invPayList.map(options => (
                                    <Radio value={options.itemCode} key={options.itemCode}>
                                      {options.itemName}
                                    </Radio>
                                  ))}
                              </RadioGroup>
                            )}
                            {item.id !== '2' &&
                            item.invMail &&
                            `${item.invMail.invPay}` === '1' &&
                            item.MailList &&
                            item.MailList.length ? (
                              <a
                                style={{
                                  position: 'absolute',
                                  right: '-65px',
                                  top: '-2px',
                                  display: 'block',
                                  width: 60,
                                }}
                                onClick={() => this.selectInvOrMail('2', item.id)}
                              >
                                选择地址
                              </a>
                            ) : null}
                          </FormItem>
                        </Col>
                        {item.invMail && `${item.invMail.invPay}` === '3' && (
                          <Col md={8} sm={24} pull={1}>
                            <FormItem label="邮箱" {...formItemLayout}>
                              {getFieldDecorator(
                                `invRulePanyTermMailDto[${item.id}][invMail][email]`,
                                {
                                  rules: [
                                    {
                                      type: 'email',
                                      required: true,
                                      message: '应为邮箱格式且长度不能超过50',
                                      pattern: /^[A-Za-z\u4e00-\u9fa5\0-9]{1,50}$/,
                                    },
                                  ],
                                  initialValue: item.invMail && item.invMail.email,
                                }
                              )(<Input placeholder="请输入" maxLength={50} />)}
                            </FormItem>
                          </Col>
                        )}
                      </Row>
                      {(item.invMail && `${item.invMail.invPay}` === '1' && (
                        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                          <Col md={8} sm={24} pull={1}>
                            <FormItem label="联系人姓名" {...formItemLayout}>
                              {getFieldDecorator(
                                `invRulePanyTermMailDto[${item.id}][invMail][contPerName]`,
                                {
                                  rules: [
                                    {
                                      required: true,
                                      message: '请输入的内容必须在1-30个字',
                                      pattern: /^[A-Za-z\u4e00-\u9fa5\0-9]{1,30}$/,
                                    },
                                  ],
                                  initialValue: item.invMail && item.invMail.contPerName,
                                }
                              )(<Input placeholder="请输入" maxLength={30} />)}
                            </FormItem>
                          </Col>
                          <Col md={8} sm={24} pull={1}>
                            <FormItem label="联系人电话" {...formItemLayout}>
                              {getFieldDecorator(
                                `invRulePanyTermMailDto[${item.id}][invMail][contPerPhone]`,
                                {
                                  rules: [
                                    {
                                      required: true,
                                      message: '请正确输入手机号码或固话(限制12位)',
                                      pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                                    },
                                  ],
                                  initialValue: item.invMail && item.invMail.contPerPhone,
                                }
                              )(<Input placeholder="请输入" maxLength={12} />)}
                            </FormItem>
                          </Col>
                          <Col md={8} sm={24} pull={1}>
                            <FormItem label="邮寄地址" {...formItemLayout}>
                              {getFieldDecorator(
                                `invRulePanyTermMailDto[${item.id}][invMail][mailArea]`,
                                {
                                  rules: [
                                    {
                                      type: 'array',
                                      required: true,
                                      message: '请选择(市区或县级)',
                                      min: 2,
                                    },
                                  ],
                                  initialValue: item.invMail && item.invMail.mailArea,
                                }
                              )(
                                <Cascader
                                  placeholder="请选择"
                                  options={provCityAreaList}
                                  loadData={this.loadAreaData}
                                  onChange={(value, selectedOptions) =>
                                    this.selectProvCityArea(value, selectedOptions, item.id)
                                  }
                                  changeOnSelect
                                />
                              )}
                            </FormItem>
                          </Col>
                          <Col md={8} sm={24} pull={1}>
                            <FormItem label="详细地址" {...formItemLayout}>
                              {getFieldDecorator(
                                `invRulePanyTermMailDto[${item.id}][invMail][mailAddr]`,
                                {
                                  rules: [
                                    { required: true, message: '请输入的内容必须在1-100个字' },
                                  ],
                                  initialValue: item.invMail && item.invMail.mailAddr,
                                }
                              )(<Input placeholder="请输入" maxLength={100} />)}
                            </FormItem>
                          </Col>
                        </Row>
                      )) ||
                        null}
                    </div>
                  ))}
              </Card>
            )}
            <SelectInvMail
              modalVisible={modalVisible}
              handleModalVisible={this.handleModalVisible}
              invMailType={invMailType}
              invMailData={invMailData}
              saveInvOrMail={this.saveInvOrMail}
              sysCode={sysCode}
              selectMailLoading={selectMailLoading}
            />
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button type="primary" onClick={this.submitData}>
                保存
              </Button>
            </FooterToolbar>
          </Form>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default EditInvRule;
